﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Ewk.Runtime.Serialization.PositionBased;

namespace Ewk.Runtime.Serialization.CustomDatafieldSerializers.PositionBased
{
    public class BooleanSerializer : DatafieldSerializer<PositionBasedDatafieldAttribute>
    {
        public override Type DatafieldType
        {
            get { return typeof(bool); }
        }

        public override string Serialize(object datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            var value = (bool)datafield;

            switch (datafieldAttribute.Format)
            {
                case "YN":
                case "yn":
                case "Y":
                case "y":
                    return value ? "Y" : "N";
                case "JN":
                case "jn":
                case "J":
                case "j":
                    return value ? "J" : "N";
                case "01":
                case "1":
                    return value ? "1" : "0";
                default:
                    return value.ToString(CultureInfo.CurrentCulture);
            }
        }

        public override object Deserialize(string datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            switch (datafieldAttribute.Format)
            {
                case "YN":
                case "yn":
                case "Y":
                case "y":
                    return datafield.ToLower() == "y" ? true : false;
                case "JN":
                case "jn":
                case "J":
                case "j":
                    return datafield.ToLower() == "j" ? true : false;
                case "01":
                case "1":
                    return datafield.ToLower() == "1" ? true : false;
                default:
                    {
                        bool result;
                        if (bool.TryParse(datafield, out result))
                        {
                            return result;
                        }

                        throw new DatafieldSerializationException();
                    }
            }
        }
    }
}
